<template>
    <el-dialog
      v-model="dialogVisible"
      title="权限设置"
      width="900px"
      :close-on-click-modal="false"
      @close="handleClose"
    >
    <div v-if="resource" class="permission-container">
      <div class="resource-info">
        <div style="display: flex; align-items: center; gap: 12px;">
          <el-tag :type="resource.type === 'file' ? 'primary' : 'success'" size="large">
            {{ resource.type === 'file' ? '文件' : '文件夹' }}
          </el-tag>
          <h3 style="margin: 0; font-size: 18px; font-weight: 500;">{{ resource.name }}</h3>
        </div>
      </div>
      
      <el-divider />
      
      <div class="permission-content">
        <div class="permission-header">
          <h4>权限管理</h4>
          <el-button type="primary" size="small" @click="handleAddPermission">
            添加权限
          </el-button>
        </div>
        
        <el-table :data="permissionList" v-loading="loading" style="width: 100%">
          <el-table-column label="用户/角色" width="250">
            <template #default="{ row }">
              <span>{{ row.userName || row.roleName }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="权限类型" width="200">
            <template #default="{ row }">
              <el-tag :type="getPermissionTypeColor(row.permissionType || '')">
                {{ getPermissionTypeText(row.permissionType || '') }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="授权类型" width="150">
            <template #default="{ row }">
              <el-tag :type="(row.grantType || '') === 'user' ? 'primary' : 'success'">
                {{ (row.grantType || '') === 'user' ? '用户' : '角色' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="(row.status || '') === '0' ? 'success' : 'danger'">
                {{ (row.status || '') === '0' ? '正常' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="handleEditPermission(row)"
              >
                编辑
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="handleDeletePermission(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加权限对话框 -->
    <AddPermissionDialog
      v-model:visible="addPermissionDialogVisible"
      :resource-type="resourceType"
      :resource-id="resourceId"
      @success="handleAddPermissionSuccess"
    />

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { permissionApi } from '@/api/cd'
import AddPermissionDialog from './AddPermissionDialog.vue'

interface Props {
  visible: boolean
  resource: { type: string; id: number | string; name: string } | null
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'permission-success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const loading = ref(false)
const permissionList = ref<any[]>([])
const addPermissionDialogVisible = ref(false)
const resourceType = computed(() => props.resource?.type === 'file' ? 'file' : 'folder')
const resourceId = computed(() => props.resource?.id || 0)

// 监听对话框打开，加载权限列表
watch(() => props.visible, async (newVal) => {
  if (newVal && props.resource) {
    await loadPermissionList()
  }
})

// 加载权限列表
const loadPermissionList = async () => {
  if (!props.resource) return
  
  loading.value = true
  try {
    const resourceType = props.resource.type === 'file' ? 'file' : 'folder'
    const response = await permissionApi.getResourcePermissions(resourceType, props.resource.id)
    permissionList.value = response.data || []
  } catch (error) {
    console.error('加载权限列表失败:', error)
    ElMessage.error('加载权限列表失败')
  } finally {
    loading.value = false
  }
}

const getPermissionTypeColor = (type: string) => {
  const colors = {
    read: 'info',
    write: 'warning',
    delete: 'danger',
    share: 'success',
    manage: 'primary'
  }
  return colors[type as keyof typeof colors] || 'info'
}

const getPermissionTypeText = (type: string) => {
  const texts = {
    read: '读取',
    write: '写入',
    delete: '删除',
    share: '分享',
    manage: '管理'
  }
  return texts[type as keyof typeof texts] || type
}

const handleAddPermission = () => {
  addPermissionDialogVisible.value = true
}

const handleAddPermissionSuccess = () => {
  ElMessage.success('权限添加成功')
  loadPermissionList()
  emit('permission-success')
}

const handleEditPermission = (row: any) => {
  // TODO: 打开编辑权限对话框
  ElMessage.info('编辑权限功能待实现')
}

const handleDeletePermission = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除此权限吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true
    try {
      await permissionApi.delete([row.permissionId])
      ElMessage.success('权限删除成功')
      await loadPermissionList()
      emit('permission-success')
    } catch (error) {
      console.error('删除权限失败:', error)
      ElMessage.error('权限删除失败')
    } finally {
      loading.value = false
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除权限取消:', error)
    }
  }
}

const handleClose = () => {
  dialogVisible.value = false
}
</script>

<style scoped lang="scss">
.permission-container {
  .resource-info {
    display: flex;
    align-items: center;
    gap: 12px;
    
    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
    }
  }
  
  .permission-content {
    .permission-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      h4 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>